package com.hubu.parking.config;

import com.hubu.parking.job.ParkingFeeCalculationJob;
import org.quartz.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {

    // 定义 JobDetail
    @Bean
    public JobDetail parkingFeeJobDetail() {
        return JobBuilder.newJob(ParkingFeeCalculationJob.class)
                .withIdentity("parkingFeeJob")  // 确保与 Trigger 关联的 Job 名称一致
                .storeDurably()
                .build();
    }

    // 定义 Trigger（每 10 秒触发一次）
    @Bean
    public Trigger parkingFeeTrigger() {
        SimpleScheduleBuilder schedule = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(10)
                .repeatForever();

        return TriggerBuilder.newTrigger()
                .forJob(parkingFeeJobDetail())  // 明确关联 JobDetail
                .withIdentity("parkingFeeTrigger")
                .withSchedule(schedule)
                .build();
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(
            JobDetail parkingFeeJobDetail,
            Trigger parkingFeeTrigger,
            ApplicationContext applicationContext) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 设置支持依赖注入的 JobFactory
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        factory.setJobFactory(jobFactory);

        factory.setJobDetails(parkingFeeJobDetail);
        factory.setTriggers(parkingFeeTrigger);
        return factory;
    }

}
